﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Antlr.Runtime;

namespace XYZCompiler
{
    class LexerPart:CompilePartBase
    {
        #region Overrides of CompilePartBase
        public override string CompilePartName
        {
            get { return "Lexer parser"; }
        }

        /// <summary>
        /// Main method of part
        /// </summary>
        /// <param name="param">input for part</param>
        /// <returns>Compile result include  state and output.Output is for next part</returns>
        public override CompilePartResult Excute(object param)
        {
            //System.Windows.Forms.MessageBox.Show(param as string);
            _hasError = false;
            var source = param as string;
            CompilerHelper.Debug("==========================");
            CompilerHelper.Debug("Start Lexer part");
            if(param ==null)
                throw  new SystemException("Lexer parser input error");
            var stream = new ANTLRStringStream(param as string);
            var lexer = new XYZLexer(stream);
            lexer.Error += ErrorHandler;
            IToken t;
            while ((t = lexer.NextToken()).Type != -1)
            {
               
             //   CompilerHelper.Debug(t.Text + t.Line.ToString() + t.CharPositionInLine.ToString());
            }
            lexer.Error -= ErrorHandler;
            lexer.Line = 1;
            lexer.CharPositionInLine = 0;
            lexer.Reset();
            var cts = new CommonTokenStream(lexer);
            //cts.Reset();
            if(!_hasError)
            {
                CompilerHelper.Debug(">>>>Id static<<<<");
                foreach (var id in lexer.id_stat)
                {
                    CompilerHelper.Debug(id.Key+":"+id.Value.ToString());
                }
                CompilerHelper.Debug(">>>>Key static<<<<");
                foreach (var key in lexer.key_stat)
                {
                    CompilerHelper.Debug(key.Key + ":" + key.Value.ToString());
                }
            }
            CompilerHelper.Debug("Lexer part End");
            CompilerHelper.Debug("==========================");
            if(_hasError)
                return new CompilePartResult(FlowController.CompileState.ERROR, cts);
            return new CompilePartResult(FlowController.CompileState.LEXER_COMPLETED, cts);
        }
        /// <summary>
        /// listen lexer error
        /// </summary>
        /// <param name="s">error string</param>
        /// <param name="c">column</param>
        /// <param name="r">row</param>
        protected void ErrorHandler(string s,int c,int r)
        {
             _hasError = true;
            CompilerHelper.Debug(string.Format("{0} ocurred in Row:{1} Column:{2}", s, r, c));
            NotifyError(s, c, r);
        }
        #endregion

    }
}
